package com.jcl.myutils.util;

import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 朝花不迟暮
 * @Description: 属性拷贝
 * @Date: 2022/3/6
 */
public class CopyUtil {

    /**
     * 对象集合拷贝
     *
     * @param source 源对象
     * @param clazz  目标对象泛型
     */
    public static <T> List<T> copyList(List source, Class<T> clazz) {
        List<T> target = new ArrayList<>();
        if (!CollectionUtils.isEmpty(source)) {
            if (!CollectionUtils.isEmpty(source)) {
                for (Object c : source) {
                    T obj = copy(c, clazz);
                    target.add(obj);
                }
            }
        }
        return target;
    }


    /**
     * 属性拷贝
     *
     * @param source 源对象
     * @param clazz  拷贝目标对象
     */
    public static <T> T copy(Object source, Class<T> clazz) {
        if (source == null) {
            return null;
        }
        T obj = null;
        try {
            obj = clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        BeanUtils.copyProperties(source, obj);
        return obj;
    }
}
